package engine.game.gfx;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteSheet {
	
	public String path;
	public int width;
	public int height;
	
	private int pixelSize;
	
	public int[] pixels;
	
	public SpriteSheet(String path, int pixelSize) {
		this.pixelSize = pixelSize;
		
		BufferedImage image = null;
		
		try {
			image = ImageIO.read(new File(path));
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		
		if (image == null) {
			return;
		}
		
		this.path = path;
		this.width = image.getWidth();
		this.height = image.getHeight();
		
		pixels = image.getRGB(0, 0, width, height, null, 0, width);
		
		for (int i = 0; i < pixels.length; i++) {
			pixels[i] = (pixels[i] & 0xFF) / 64;
		}
	}
	
	
	// Returns a sprite with top left corner at the x and y locations on the sprite grid with the widths and heights provided (in basic pixel grid units)
	public Sprite getSprite(int x, int y, int gridWidth, int gridHeight) {
		if (gridWidth == 1 && gridHeight == 1) {
			return getBasicSprite(x, y);
		}
		
		BasicSprite[][] componentSprites = new BasicSprite[gridWidth][gridHeight];
		
		for (int xPos = 0; xPos < gridWidth; xPos++) {
			for (int yPos = 0; yPos < gridHeight; yPos++) {
				componentSprites[xPos][yPos] = getBasicSprite(x + xPos, y + yPos);
			}
		}
		
		return new CompositeSprite(componentSprites);
	}
	
	// Returns a sprite of width and height equal to the base pixel size located at the grid location specified.
	public BasicSprite getBasicSprite(int x, int y) {
		int[] pixels = new int[pixelSize * pixelSize];
		
		int xPos = x * pixelSize;
		int yPos = y * pixelSize;
		
		for (int j = 0; j < pixelSize; j++) {
			for (int i = 0; i < pixelSize; i++) {
				pixels[i + (j * pixelSize)] = this.pixels[(xPos + i) + ((yPos + j) * 32 * pixelSize)];
			}
		}
		
		return new BasicSprite(pixels, pixelSize, pixelSize);
	}
}
